import axios from "axios";
import React, { useState, useEffect } from "react";

// 消抖

const request = async (url) => {
  const resp = await axios.get(url);
  const data = resp.data;
  if (data.code !== 200) {
    alert("服务器开小差了");
    return {};
  }
  return data.data;
};

const GetUser = () => {
  const [user, setUser] = useState({});
    const [id, setId] = useState(9527);
    const [loading, setLoading] = useState(false);

    const getUser = async () => {
      setLoading(true);
    const user = await request(`https://xiaozhu.run/api/user/${id}`);
      setLoading(false);
    setUser(user);
  };

  useEffect(() => getUser(), [id]);

  // useEffect( () => {
  //     axios
  //         .get("http://xiaozhu.run/api/user/9527")
  //         .then(resp => {
  //             const data = resp.data;
  //             if (data.code !== 200) {
  //                 alert("服务器开小差了");
  //                 return {};
  //             }
  //             return data.data;
  //         }).then(user => setUser(user));
  // }, []);

  return (
    <div>
      <button
        onClick={() => {
          setId(id + 1);
        }}
      >
        GetUser {id}
          </button>
        {/* 判断加载是否成功 */}
      {loading && <span>Loading...</span>}
      <div>Username: {user.username}</div>
      <div>Email: {user.email}</div>
    </div>
  );
};

export default GetUser;
